<template>
<div class="mapContainer">
  <div class="searchPanel">
    <el-row :gutter="24">
      <el-col :span="20">
        <el-select v-model="currentCode" placeholder="请选择" @change="areaChange" size="medium">
          <el-option v-for="item in areaOptions" :key="item.code" :label="item.name" :value="item.code">
          </el-option>
        </el-select>
        <el-button :type="currentIndex == -1 ? 'danger' : ''" @click="getCurrentGround({}, -1)" class="ml10" size="medium">全部</el-button>
        <el-button size="medium" v-for="(item, index) in groundTypeOptions" :key="index" :type="index == currentIndex ? 'danger' : ''" @click="getCurrentGround(item, index)">{{ item.name }}</el-button>
      </el-col>
      <el-col :span="4"> 当前可视区域共有 {{ getNum() }} 个场点 </el-col>
    </el-row>
  </div>
  <div class="map">
    <div ref="groundMap" style="width: 100%; height: 100%" id="groundMap"></div>
  </div>
</div>
</template>
<script>
import {
  treeDataTranslate
} from "@/utils";
import type1Icon from "@/assets/type11.png";
import type2Icon from "@/assets/type12.png";
import type3Icon from "@/assets/type13.png";
import type4Icon from "@/assets/type14.png";
import mapMixin from "./mixin.js";
import {
  RadarOverlay
} from "./overlay";
import {
  RadarCircleOverlay
} from "./circleOverlay";
export default {
  mixins: [mapMixin],
  data() {
    return {
      currentCode: null,
      areaOptions: [],
      areaProps: {
        value: "code",
        label: "name",
      },
      currentIndex: -1,
      currentType: "-1",
      groundTypeOptions: [],
      currentMarkers: [],
      statisticsData: [],
      moreImg: require("@/assets/more.png"),
      dialogVisible: false,
    };
  },
  created() {
    this.initData();
  },
  mounted() {},
  methods: {
    initData() {
      this.$api
        .getDicOptions({
          params: {
            dictCode: "GroundType",
          },
        })
        .then((res) => {
          this.groundTypeOptions = res;
        })
        .catch((err) => {
          this.$message.error(err);
        });
      this.$api
        .getAllArea({
          levels: ["province", "city", "district"],
        })
        .then((res) => {
          res.splice(
            res.findIndex((item) => item.level === "city"),
            1
          );
          this.areaOptions = res;
          this.currentCode = this.areaOptions.find(
            (x) => x.name == "北京市"
          ).code;
        })
        .catch((err) => {
          this.$message.error(err);
        });
    },
    areaChange(val) {
      let me = this;
      if (val == me.areaOptions.find((x) => x.name == "北京市").code) {
        //切换到北京市，显示统计数，
        me.mapInit.centerAndZoom(me.defaultCenter, me.defaultZoom);
        me.getStatistics();
      } else {
        //切换到具体区时，将地图中心点设置为当前区的center,将比例调整为ZOOMBOUNDARY
        let obj = me.statisticsData.filter((x) => x.districtCode == val)[0];
        var point = new BMapGL.Point(obj.center[0], obj.center[1]);
        me.mapInit.centerAndZoom(point, me.ZOOMBOUNDARY);
        // me.getNearGround()
      }
    },
    getCurrentGround(item, index) {
      let me = this;
      me.clearAllOverlays();
      me.currentType = item.id || "-1";
      me.currentIndex = index;
      if (
        me.currentCode != me.areaOptions.find((x) => x.name == "北京市").code
      ) {
        let obj = me.statisticsData.filter(
          (x) => x.districtCode == me.currentCode
        )[0];
        var point = new BMapGL.Point(obj.center[0], obj.center[1]);
        if (me.zoom < me.ZOOMBOUNDARY) {
          me.mapInit.centerAndZoom(point, me.ZOOMBOUNDARY);
        } else {
          me.mapInit.centerAndZoom(point, me.zoom);
        }
      } else {
        me.mapInit.centerAndZoom(me.defaultCenter, me.defaultZoom);
        me.getStatistics();
      }
    },
    getNum() {
      if (this.zoom >= this.ZOOMBOUNDARY) {
        return this.currentMarkers ? this.currentMarkers.length : 0;
      } else {
        if (this.mapInit) {
          return this.mapInit.getOverlays().length;
        } else {
          return 0;
        }
      }
    },
    getNearGround() {
      let me = this;
      let params = {};
      if (me.currentType == "-1") {
        params = {
          center: me.center,
          scale: me.zoom,
          vertex: me.vertexPoint,
        };
      } else {
        params = {
          center: me.center,
          groundType: me.currentType,
          scale: me.zoom,
          vertex: me.vertexPoint,
        };
      }
      me.$api.getNearByGround(params).then((res) => {
        me.currentMarkers = res;
        if (res.length > 0) {
          me.createMarker(res);
        }
      });
    },
    //添加具体点位覆盖物
    createMarker(data) {
      let me = this;
      data.forEach((item, i) => {
        var pt = new BMapGL.Point(
          item.coordinate.split(",")[0],
          item.coordinate.split(",")[1]
        );
        var marker = new BMapGL.Marker(pt);
        let iconUrl = "";
        if (item.groundType == "1") {
          iconUrl = type1Icon;
        } else if (item.groundType == "2") {
          iconUrl = type2Icon;
        } else if (item.groundType == "3") {
          iconUrl = type3Icon;
        } else {
          iconUrl = type4Icon;
        }
        var opts = {
          title: item.groundName,
          enableCloseOnClick: false, //单击地图时关闭infoWindow
        };
        let imgUrl =
          url.baseUrl + "admin/upms/file/download?filename=" + item.photos[0];
        var content =
          "<div class='infoWindow'>" +
          // "<p style='text-align:center' class=''></p>" +
          "<p style='text-align:center;background:url(" +
          imgUrl +
          ");background-size:cover;background-position:center' class='infoWindowGroundImg'></p>" +
          "<p class='mt8 oneline'>地址：" +
          item.address +
          "</p>" +
          "<p class='distAlign tel'><span style='width: calc(100% - 63px);text-overflow: ellipsis;white-space: nowrap;overflow: hidden;'>咨询电话：" +
          item.tel +
          "</span>" +
          "<span class='detailBtn' id='detailBtn'>详情<img src='" +
          this.moreImg +
          "' class='moreImg'></img></span></p></div>";
        var infoWindow = new BMapGL.InfoWindow(content, opts);
        marker.setIcon(new BMapGL.Icon(iconUrl, new BMapGL.Size(30, 30)));
        marker.addEventListener("click", function() {
          me.mapInit.openInfoWindow(infoWindow, pt); // 开启信息窗口
        });
        if (!infoWindow.isOpen()) {
          infoWindow.addEventListener("open", function() {
            var btn = document.getElementById("detailBtn");
            btn.addEventListener("click", function() {
              const {
                href
              } = me.$router.resolve({
                name: 'detailPage',
                query: {
                  id: item.groundId
                }
              })
              let test = window.open(href, '_blank')
              test.onload = function() {
                test.document.title = item.groundName
              }
            });
          });
        } else {
          var btn = document.getElementById("detailBtn");
          btn.addEventListener("click", function() {
            const {
              href
            } = me.$router.resolve({
              name: 'detailPage',
              query: {
                id: item.groundId
              }
            })
            // window.open(href, '_blank')
            let test = window.open(href, '_blank')
            test.onload = function() {
              test.document.title = item.groundName
            }
          });
        }

        // 将标注添加到地图
        me.mapInit.addOverlay(marker);
      });
    },

    //获取统计数
    getStatistics() {
      let me = this;
      me.$api.getStatistics().then((res) => {
        me.statisticsData = res;
        me.createOverLay(res);
      });
    },
    //添加自定义覆盖物（按地区统计数）
    createOverLay(data) {
      let me = this;
      for (let i = 0; i < data.length; i++) {
        let properties = {};
        let arr = data[i].children.map((x) => {
          return me.getTypeName(x.groundType) + "：" + x.total;
        });
        if (me.currentIndex == -1) {
          //显示全部统计数
          properties = {
            title: data[i].districtName,
            statisText: arr,
          };
          var point = new BMapGL.Point(data[i].center[0], data[i].center[1]);
          const radar = new RadarCircleOverlay(point, properties);
          me.mapInit.addOverlay(radar);
          radar.addEventListener("click", function(e) {
            var center = new BMapGL.Point(data[i].center[0], data[i].center[1]);
            me.mapInit.centerAndZoom(center, me.ZOOMBOUNDARY);
            me.$set(me, "currentCode", data[i].districtCode);
            // me.clearAllOverlays()
            // me.getNearGround()
          });
        } else {
          //显示当前类型统计数
          properties = {
            title: data[i].districtName,
            text: me.getTypeName(me.currentType) + "：",
            num: data[i].children.filter(
              (x) => x.groundType == me.currentType
            )[0].total,
          };
          var point = new BMapGL.Point(data[i].center[0], data[i].center[1]);
          const radar = new RadarOverlay(point, properties);
          me.mapInit.addOverlay(radar);
          radar.addEventListener("click", function(e) {
            var center = new BMapGL.Point(data[i].center[0], data[i].center[1]);
            me.mapInit.centerAndZoom(center, me.ZOOMBOUNDARY);
            // me.clearAllOverlays()
            // me.getNearGround()
          });
        }
      }
    },
    handleQuery() {
      let me = this;
      me.clearAllOverlays();
      if (me.zoom >= me.ZOOMBOUNDARY) {
        me.getNearGround();
      } else {
        me.getStatistics();
      }
    },
    clearAllOverlays() {
      let me = this;
      var allOverlay = me.mapInit.getOverlays();
      for (var i = 0; i < allOverlay.length; i++) {
        me.mapInit.removeOverlay(allOverlay[i]);
      }
    },
  },
};
</script>

<style lang="less">
.mapContainer {
    width: 100%;
    height: 100%;
    overflow: hidden;
    font-size: 14px;
    .searchPanel {
        width: 100%;
        height: 50px;
        line-height: 50px;
        border-bottom: 1px solid #f3f3f3;
        padding: 10px 20px;
    }
    .map {
        width: 100%;
        height: calc(100vh - 100px);
    }
}
</style>
